<!doctype html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<link href="../css/mui.min.css" rel="stylesheet" />
		<link href="../css/together.css" rel="stylesheet"  />
		<style type="text/css">
			
			.numcss{
				width: 100%;
				display: flex;
				align-items:center ;
				justify-content: space-between;
				padding: 11px 15px;
				background-color: white;
				
			}
			.inpcss{
				background-color: white;
				border-bottom: 1px solid #C7C7C7;
			}
			
			.paysbottom {
			    display: flex;
			    justify-content: space-between;
			    align-items: center;
			    background: #fff!important;
			    border-top: 0;
			    padding: 15px 10px;
			}
		</style>
	</head>
	
	<body>
		<header class="mui-bar mui-bar-nav m_barC">
		    <a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
		    <h1 class="mui-title">渭书收银台</h1>
		</header>
		<div class="mui-content">
			<div class="" id="popdiv">
				<ul class="mui-table-view">
				        <li class="mui-table-view-cell">
				            <a class="mui-navigate-right" id="addcssid">
				               暂无地址,点击设置
				            </a>
				        </li>
				    </ul>
				
			</div>
			<div class="">
				<ul class="mui-table-view" id="booklist">
				    
				</ul>
			</div>
			<div class="numcss">
				<div class="">
				数量：
				</div>	
				<div class="mui-numbox" data-numbox-step='1' data-numbox-min='1' data-numbox-max='1000'>
				    <button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
				    <input class="mui-input-numbox" type="number" id="num"/>
				    <button class="mui-btn mui-btn-numbox-plus" type="button">+</button>
				</div>
			</div>
			<div class="inpcss">
				<div class="mui-input-row">
				    <label>备注：</label>
				    <input id="preference" type="text" placeholder="输入备注">
				</div>
				
			</div>
			<div class="paystop">
				支付方式
			</div>
			
				<div class="paysbottom  mui-input-row mui-radio mui-right">
						<label class="paysbl ">
								<img class="weiimg" src="../images/wx2.png" alt="" />
								<div>
									微信支付
									<span>微信安全支付</span>
								</div>
						</label>
					<input type="radio" checked="checked"/>
				</div>
			</div>
			<div class="wxpay" id="btn_pay">
				下单
			</div>
		<script src="../js/jquery.min.js" type="text/javascript" charset="utf-8"></script>	
		<script src="../js/mui.min.js"></script>
		<script src="../js/req.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/muishow.js" type="text/javascript" charset="utf-8"></script>
		<script src="../js/pay.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			 var channel = null;	//支付通道
			 var sid = 0;			//商品id
			 	 addid = 0;			//地址id
			
		
			
			window.onload = function(){
				mui.init();
				
				sid = getrequest().sid||4;
				console.log(sid)
				mui.plusReady(function(){
                //获取支付通道
              
	               getChannels();
	                
	            });
	            
	            
            	g("btn_pay").addEventListener("tap",function(){
                    orderAdd();
                    //pay2()
                   
                })
				 
				orderPreview(); 
			}
			
			function orderAdd(){
				var num = g("num").value||1;
				var data = {
					url:"/api/Order/orderAdd",
					data:{
						access_token:acctoken(),
						bid:4||sid,
						address_id:29||addid,
						preference:g("preference").value||"",
						num:num,
					}
				}
				ajax(data,function(res){
					console.log(res);
					var data = {
						"appid":res.data[0].appid,
						"partnerid":res.data[0].mch_id,
						"prepayid":res.data[0].prepay_id,
						"package":"Sign=WXPay",
						"noncestr":res.data[0].nonce_str,
						"timestamp":res.data[0].timestamp,
						"sign":res.data[0].sign,
					}
					//pay(data);
					 pay3("",JSON.stringify(data));
				})
			}
			
			//发起微信支付请求的方法
                function pay(data){
	                plus.payment.request(channel,data,function(result){  
	                    plus.nativeUI.alert("支付成功！",function(){
	                    	setTimeout(function(e){
	                    		mui.back();  
	                    	},500)
	                    });  
	                },function(error){  
	                	console.log(JSON.stringify(error));
	                    plus.nativeUI.alert("支付失败：" + JSON.stringify(error));  
	                });  
          
                }
                
                /**
             * 支付
             * @param {Object} payType  支付类型
             * @param {Object} payStatement  调起支付宝或微信的statment支付订单信息
             */
            function pay3(payType, payStatement) {
                /***判断支付通道****/
                //最终的支付通道
                var channel;
                /***
                 * 用于标识支付通道： 
                 * "alipay" - 表示支付宝；
                 * "wxpay" - 表示微信支付； 
                 */
                var payId; //支付标识
                if(payType == "ALIPAY_ANDROID") {
                    payId = "alipay";
                } else {
                    payId = "wxpay";
                }

                // 取出支付宝和微信的支付通道
                plus.payment.getChannels(function(channels) {
                    mui.each(channels, function(index, element) {
                        if(element.id == payId) {
                            channel = element;
                        }
                    });
                    if(!channel) {
                        mui.toast('获取支付通道失败，请重试！');
                    }
                    //发起支付
                    plus.payment.request(channel, payStatement, function(result) {
                        mui.toast('支付完成');
                        /**
                         *查询订单状态是否已支付
                         * 轮询查询订单状态
                         * 
                         */
                        

                    }, function(error) {
                        console.log(JSON.stringify(error));
                        mui.toast("支付失败");
                        plus.nativeUI.alert("支付失败：" + JSON.stringify(error));  
                    });

                }, function(e) {
                    mui.toast("获取支付通道列表失败：" + e.message);
                });
            }
			
			//订单预览
			function orderPreview(){
				var data = {
					url:"/api/Order/orderPreview",
					data:{
						access_token:acctoken(),
						bid:sid,
					}
				}
				ajax(data,function(res){
					console.log("预订单",res);
					
					if(res.data.length){
						if(res.data[0].address_list){
							setaddress(res.data[0].address_list);
						}
						if(res.data[0].book_info.length){
							setbook(res.data[0].book_info)
						}
					}
					
				})
			}
			//设置地址
			function setaddress(list){
				addid = list[0].id;
				addstr = list[0].province+' '+list[0].city+' '+list[0].county+' '+list[0].address;
				g("addcssid").innerHTML = addstr;
			}
			//设置书本
			function setbook(list){
				console.log(list)
				var str = `<li class="mui-table-view-cell mui-media" >
				        <a href="javascript:;">
				            <img class="mui-media-object mui-pull-left" src="http://placehold.it/40x30">
				            <div class="mui-media-body">
				                ${list[0].title}
				                <p class="mui-ellipsis">${list[0].introduction}</p>
				            </div>
				        </a>
				    </li>`
				g("booklist").innerHTML = str;
			}
			
			function get_address(data){
				let list = {
					url:"/api/Address/address_list",
					data:{access_token:acctoken()}
				}
				ajax(list,function(res){
					console.log("地址详情",res);
					if(res.data.length){
						for(let i = 0; i < res.data.length;i++){
							if(res.data[i].status == 1){
								addid = res.data[i].id;
								addstr = res.data[i].province+' '+res.data[i].city+' '+res.data[i].county+' '+res.data[i].address;
							}
						}
						g("addcssid").innerHTML = addstr;
					}
				})
			}
			 //获取支付通道的方法
			 function getChannels(){
                    plus.payment.getChannels(function(channels) {
                        for (var i = 0; i < channels.length; i++) {
                            if (channels[i].id == "wxpay") {
                                channel = channels[i];
                            }
                        }
                        //plus.ui.toast("使用支付方式:" + channel.id);
                    }, function(e) {
                        plus.ui.toast("获取支付通道失败!");
                        console.log("获取支付通道失败!");
                    })
            }
			function pay2(){
				
				var WXPAYSERVER = 'http://demo.dcloud.net.cn/payment/wxpayv3.HBuilder/?total=0.01'
                 var PAYSERVER = WXPAYSERVER;
                 mui.ajax(PAYSERVER,{
                        data:"",
                        dataType:"json",
                        type:"get",
                        success:ajax_success_callback,
                        error:ajax_error_callback
                    })
                 
				
			}
                
              
                      //获取微信支付参数成功的回调函数
                function ajax_success_callback(resObj){
                    console.log("请求微信支付参数成功,返回的json:");
                    var res_str=JSON.stringify(resObj);
                    console.log(res_str);
                    //用返回参数 发起微信支付请求
                    plus.payment.request(channel,res_str,wxpay_success,wxpay_error);
                }
                //获取微信支付参数失败的回调函数
                function ajax_error_callback(e){
                    console.log("ajax获取参数失败");
                }
                //微信支付成功回调
                function wxpay_success(result){
                    plus.ui.alert("支付成功!",function()
                    {
                        mui.back();
                    })
                }
                   //微信支付失败回调
                function wxpay_error(error){
                	console.log(JSON.stringify(error))
                	plus.ui.alert(JSON.stringify(error));
                    plus.ui.alert("支付失败!");
//                    plus.ui.alert(JSON.stringify(error));
//                    console.log(JSON.stringify(error));
                }     
                
                
                
                /*
                     var xhr=new XMLHttpRequest();  
    xhr.onreadystatechange=function(){  
        switch(xhr.readyState){  
            case 4:  
            if(xhr.status==200){  
                plus.payment.request(channel,xhr.responseText,function(result){  
                    plus.nativeUI.alert("支付成功！",function(){  
                        mui.back();  
                    });  
                },function(error){  
                	console.log(JSON.stringify(error));
                    plus.nativeUI.alert("支付失败：" + error.code);  
                });  
            }else{  
                alert("获取订单信息失败！");  
            }  
            break;  
            default:  
            break;  
        }  
    }  
    xhr.open('GET',PAYSERVER);  
    xhr.send(); 
    
    
     return;
                 //获取微信支付参数的url
                 var WXPAYSERVER = 'http://demo.dcloud.net.cn/payment/wxpayv3.HBuilder/?total=0.01'
                 var PAYSERVER = WXPAYSERVER;
                 mui.ajax(PAYSERVER,{
                        data:"",
                        dataType:"json",
                        type:"get",
                        success:ajax_success_callback,
                        error:ajax_error_callback
                    })
                    
                    
                      //获取微信支付参数成功的回调函数
                function ajax_success_callback(resObj){
                    console.log("请求微信支付参数成功,返回的json:");
                    var res_str=JSON.stringify(resObj);
                    console.log(res_str);
                    //用返回参数 发起微信支付请求
                    plus.payment.request(channel,res_str,wxpay_success,wxpay_error);
                }
                //获取微信支付参数失败的回调函数
                function ajax_error_callback(e){
                    console.log("ajax获取参数失败");
                }
                //微信支付成功回调
                function wxpay_success(result){
                    plus.ui.alert("支付成功!",function()
                    {
                        mui.back();
                    })
                }
                   //微信支付失败回调
                function wxpay_error(error){
                	console.log(JSON.stringify(error))
                	plus.ui.alert(JSON.stringify(error));
                    plus.ui.alert("支付失败!");
//                    plus.ui.alert(JSON.stringify(error));
//                    console.log(JSON.stringify(error));
                }
    * 
    * 
    * */
		</script>
	</body>

</html>